import 'package:flutter_axrjc/datasource/network/api/KnowledgeApi.dart';
import 'package:flutter_axrjc/datasource/network/bean/ArticleBean.dart';
import 'package:flutter_axrjc/datasource/network/bean/AssetBean.dart';
import 'package:flutter_axrjc/datasource/network/request/exp.dart';
import 'package:flutter_axrjc/widget/image_picker_dialog.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:get/get.dart';
import 'package:image_cropper/image_cropper.dart';

import 'state.dart';

class EditArticleLogic extends GetxController {
  final EditArticleState state = EditArticleState();
  late ArticleBean bean;

  @override
  void onInit() {
    super.onInit();
    bean = Get.arguments as ArticleBean;
    state.title.value = bean.articleTitle ?? '';
    state.homePic.value = bean.articelHomePic ?? '';
    state.content.value = bean.articleContent ?? '';
    refreshImg();
  }

  Future<void> change() async {
    try {
      await KnowledgeApi.changeArticle(
        articelHomePic: state.homePic.value,
        articleContent: state.content.value,
        articleTitle: state.title.value,
        articleId: "${bean.articleId}",
        imgFile: state.imgList
            .where((p0) => p0.isLocal && p0.pathOrUrl != "add")
            .map((e) => e.pathOrUrl)
            .toList(),
      );
      Get.back();
      EasyLoading.showToast("修改成功");
    } on ApiException catch (e) {
      EasyLoading.showToast(e.message);
    } catch (e) {
      EasyLoading.showToast("$e");
    }
  }

  Future<void> selectHomePic() async {
    AssetBean? a = await showSingleMedia();
    if (a == null) {
      return;
    }
    state.homePic.value = a.path;
  }

  Future<void> addImg() async {
    AssetBean? a = await showSingleMedia();
    if (a == null) {
      return;
    }

    CroppedFile? file = await ImageCropper().cropImage(sourcePath: a.path);
    if (file == null) {
      return;
    }
    state.imgList.add(ArticleImgBean(
        pathOrUrl: file.path, isLocal: true, ifUploadedFileNo: ''));
  }

  void refreshImg() {
    state.imgList.clear();
    state.imgList.addAll((bean.filePathList ?? [])
        .map((e) => ArticleImgBean(
            pathOrUrl: "${e.filePath}",
            isLocal: false,
            ifUploadedFileNo: '${e.fileNo}'))
        .toList());

    state.imgList.add(
        ArticleImgBean(pathOrUrl: "add", isLocal: true, ifUploadedFileNo: ''));
  }
}
